"""
加密工具
用于敏感数据的加密和解密（AES-256）
"""
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import base64
import os
from config.settings import settings


class CryptoService:
    """加密服务"""
    
    def __init__(self, key: str = None):
        """
        初始化加密服务
        
        Args:
            key: 加密密钥，如果不提供则使用配置中的密钥
        """
        self.key = key or settings.SECRET_KEY
        self._fernet = self._create_fernet()
    
    def _create_fernet(self) -> Fernet:
        """创建 Fernet 实例"""
        # 使用 PBKDF2HMAC 从密钥派生加密密钥
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=b'sac_ssl_cert_salt',  # 固定 salt，生产环境应该使用随机 salt 并存储
            iterations=100000,
            backend=default_backend()
        )
        
        key = base64.urlsafe_b64encode(kdf.derive(self.key.encode()))
        return Fernet(key)
    
    def encrypt(self, plaintext: str) -> str:
        """
        加密字符串
        
        Args:
            plaintext: 明文
        
        Returns:
            str: 加密后的 base64 字符串
        """
        if not plaintext:
            return ""
        
        encrypted = self._fernet.encrypt(plaintext.encode())
        return base64.b64encode(encrypted).decode()
    
    def decrypt(self, ciphertext: str) -> str:
        """
        解密字符串
        
        Args:
            ciphertext: 加密的 base64 字符串
        
        Returns:
            str: 解密后的明文
        """
        if not ciphertext:
            return ""
        
        try:
            encrypted = base64.b64decode(ciphertext.encode())
            decrypted = self._fernet.decrypt(encrypted)
            return decrypted.decode()
        except Exception as e:
            raise ValueError(f"解密失败: {str(e)}")
    
    def encrypt_private_key(self, private_key_pem: str) -> str:
        """
        加密私钥
        
        Args:
            private_key_pem: PEM 格式的私钥
        
        Returns:
            str: 加密后的私钥
        """
        return self.encrypt(private_key_pem)
    
    def decrypt_private_key(self, encrypted_key: str) -> str:
        """
        解密私钥
        
        Args:
            encrypted_key: 加密的私钥
        
        Returns:
            str: PEM 格式的私钥
        """
        return self.decrypt(encrypted_key)


# 全局加密服务实例
crypto_service = CryptoService()


def encrypt_data(data: str) -> str:
    """快捷加密函数"""
    return crypto_service.encrypt(data)


def decrypt_data(data: str) -> str:
    """快捷解密函数"""
    return crypto_service.decrypt(data)

